<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>图片跟随鼠标</title>
    <style>
      * {
        margin: 0;
        padding: 0;
      }
      body {
        width: 100%;
      }
      #container {
        margin: 30px auto;
        width: 100%;
        height: 700px;
        display: block;
        position: relative;
        border-radius: 10px;
      }
      #container::after {
        content: "";
        background: url(img/bg1.jpg) no-repeat center center;
        opacity: 0.2;
        top: 0;
        left: 0;
        bottom: 0;
        right: 0;
        position: absolute;
        z-index: -1;
        background-size: 100%;
        border-radius: 10px;
      }
      #container img {
        width: 5%;
        position: absolute;
        top: 10px;
        left: 10px;
      }
    </style>
  </head>
  <body>
    <div id="container">
      <img src="img/butterfly.png" alt="" srcset="" />
    </div>
    <script>
      // 获取蝴蝶图片，注意它的样式要设置position: absolute，不占位才能移动
      var butterfly = document.querySelector("#container img");
      // 为页面添加mousemove事件
      document.addEventListener("mousemove", function (e) {
        // 使用事件对象的pageX和pageY获取鼠标的x,y坐标
        var x = e.pageX;
        var y = e.pageY;
        // 设置蝴蝶图片跟随鼠标，注意要为left和top属性添加单位"px"
        butterfly.style.left = x - 10 + "px";
        butterfly.style.top = y - 10 + "px";
      });
    </script>
  </body>
</html>
